
import {  Node, Vec3, tween, easing, ITweenOption} from 'cc';

export function QtJumpPosition(node : Node,to: Vec3, jumpHeight: number, jumpNum: number, duration: number, opts?: ITweenOption) {
    const tweenPos = new Vec3();
    const jumpTween = tween(node);
    const totalNum = jumpNum * 2;

    (node as any).jumpY = 0;
    let startPosY = 0;
    const yUpTween = tween().to(duration / totalNum, { jumpY: jumpHeight }, {
        onStart: (target: any) => {
            startPosY = target.position.y;
            target.jumpY = 0;
        },
        onUpdate: (target: any, ratio) => {
            tweenPos.set(target.position);
            tweenPos.y = startPosY + target.jumpY;
            target.position = tweenPos;
        },
        onComplete: (target: any) => {
            target.jumpY = 0;
        }, easing: 'quadOut'
    }).to(duration / totalNum, { jumpY: jumpHeight }, {
        onStart: (target: Node) => {
            startPosY = target.position.y;
        },
        onUpdate: (target: any, ratio) => {
            tweenPos.set(target.position);
            tweenPos.y = startPosY - target.jumpY;
            target.position = tweenPos;
        },
        onComplete: (target: any) => {
            target.jumpY = 0;
        }, easing: 'quadIn',
    }).union().repeat(jumpNum);

    (node as any).jumpOffsetY = 0;
    let offsetY = 0;
    const offsetYTween = tween().to(duration, { jumpOffsetY: to.y - node.position.y }, {
        onStart: (target: any) => {
            offsetY = to.y - target.position.y;
            target.jumpOffsetY = 0;
        },
        onUpdate: (target: Node, ratio) => {
            const interpOffsetY = easing.quadOut(ratio) * offsetY;
            tweenPos.set(target.position);
            tweenPos.y += interpOffsetY;
            target.position = tweenPos;
        },
        onComplete: (target: any) => {
            target.jumpOffsetY = 0;
        }, easing: 'quadOut'
    });

    (node as any).jumpX = node.position.x;
    (node as any).jumpZ = node.position.z;
    const xzTween = tween().to(duration, { jumpX: to.x, jumpZ: to.z }, {
        onStart: opts?.onStart,
        onUpdate: (target: any, ratio) => {
            tweenPos.set(target.position);
            tweenPos.x = target.jumpX;
            tweenPos.z = target.jumpZ;
            target.position = tweenPos;
            opts?.onUpdate?.();
        },
        onComplete: (target: any) => {
            // delete target.jumpX;
            // delete target.jumpY;
            // delete target.jumpZ;
            // delete target.jumpOffsetY;
            target.jumpX = target.position.x;
            target.jumpZ = target.position.z;
            opts?.onComplete?.();
        }
    })

    jumpTween.parallel(yUpTween, offsetYTween, xzTween);
    return jumpTween;
}
